<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;


/**
 * @property integer $id
 * @property string $label
 * @property string $key
 * @property string $value
 * @property string $type
 * @property string $remark
 * @property string $group
 * @property Carbon $created_at
 * @property Carbon $updated_at
 */
class SystemConfig extends Model
{
    protected $guarded = [];

    public static function getValue($key, $default = null)
    {
        $cacheKey = 'system_config:key:' . $key;
        return Cache::remember($cacheKey, 60 * 5, function () use ($key, $default) {
            return optional(self::query()->where('key', $key)->value('value')) ?? $default;
        });
    }

    public function getValueAttribute($value)
    {
        return match ($this->type) {
            'int' => (int)$value,
            'bool' => (bool)$value,
            'array' => json_decode($value, true),
            default => (string)$value,
        };
    }
}

